package com.tanhua.server.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.VisitorsApi;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.dubbo.server.pojo.Visitors;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.pojo.User;
import com.tanhua.server.pojo.UserInfo;
import com.tanhua.server.utils.RelativeDateFormat;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.Movements;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.PicUploadResult;
import com.tanhua.server.vo.VisitorsVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * @Author: JinboYang
 * @Description:
 * @Date: Created in 下午 20:51 2021/1/5
 * @ModifiedBy:
 */
@Service
public class MovementsService {

    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private PicUploadService picUploadService;

    @Autowired
    private UserInfoService userInfoService;

    @Reference(version = "1.0.0")
    private VisitorsApi visitorsApi;

    public String savePublish(String textContent,
                              String location,
                              String longitude,
                              String latitude,
                              MultipartFile[] multipartFile,
                              String token) {

        User user = this.userService.queryUserByToken(token);
        if (null == user) {
            return null;
        }

        //创建新的发布对象
        Publish publish = new Publish();
        publish.setUserId(user.getId());
        publish.setText(textContent);
        publish.setLongitude(longitude);
        publish.setLatitude(latitude);
        publish.setLocationName(location);
        publish.setSeeType(1);

        List<String> picUrls = new ArrayList<>();

        //处理上传的图片使用阿里云保存
        for (MultipartFile file : multipartFile) {
            PicUploadResult picUploadResult = this.picUploadService.upload(file);
            picUrls.add(picUploadResult.getName());
        }
        publish.setMedias(picUrls);
        return this.quanZiApi.savePublish(publish);
    }

    /**
     * @Description: 查询好友的发布列表
     * @Param:[page, pageSize]
     * @return:com.tanhua.server.vo.PageResult
     * @Author:JinboYang
     * @Date:2021/1/7
     */
    public PageResult queryPublishList(User user, Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        //如果userid为空则默认查询的是推荐
        Long userId = null;
        PageInfo<Publish> pageInfo = null;
        if (user == null) {
            String key = "QUANZI_PUBLISH_RECOMMEND_" + UserThreadLocal.get().getId();
            String value = this.redisTemplate.opsForValue().get(key);
            if (StringUtils.isNotEmpty(value)) {
                //命中了数据
                String[] pids = StringUtils.split(value, ",");
                int startIndex = (page - 1) * pageSize;
                if (startIndex < pids.length) {
                    int endIndex = startIndex + pageSize - 1;
                    if (endIndex >= pids.length) {
                        endIndex = pids.length - 1;
                    }
                    List<Long> pidList = new ArrayList<>();
                    for (int i = startIndex; i <= endIndex; i++) {
                        pidList.add(Long.valueOf(pids[i]));
                    }

                    List<Publish> publishList = this.quanZiApi.queryPublishByPids(pidList);
                    pageInfo = new PageInfo<>();
                    pageInfo.setRecords(publishList);
                }
            }
        }

        if (pageInfo == null) {
            if (user != null) {
                //查询好友动态
                userId = user.getId();
            }
            //查询dubbo获取好友列表
            pageInfo = this.quanZiApi.queryPublishList(userId, page, pageSize);
        }

        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        pageResult.setPages(0);
        pageResult.setCounts(0);

        List<Publish> records = pageInfo.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            //无动态消息
            return pageResult;
        }
        List<Movements> movementsList = new ArrayList<>();
        List<Long> userIds = new ArrayList<>();
        for (Publish record : records) {
            Movements movements = new Movements();
            movements.setUserId(record.getUserId());
            movements.setId(record.getId().toHexString());
            movements.setImageContent(record.getMedias().toArray(new String[]{}));
            movements.setTextContent(record.getText());
            movements.setCreateDate(RelativeDateFormat.format(new Date(record.getCreated())));

            movements.setDistance("1.2公里");
            movements.setCommentCount(10);


            String likeUserCommentKey = "QUANZI_COMMENT_LIKE_USER_" + UserThreadLocal.get().getId() + "_" + record.getId().toHexString();
            movements.setHasLiked(this.redisTemplate.hasKey(likeUserCommentKey) ? 1 : 0); //TODO 是否点赞（1是，0否）

            String likeCommentKey = "QUANZI_COMMENT_LIKE_" + record.getId().toHexString();
            String data = this.redisTemplate.opsForValue().get(likeCommentKey);
            if (StringUtils.isNotEmpty(data)) {
                movements.setLikeCount(Integer.valueOf(data)); //TODO 点赞数
            } else {
                movements.setLikeCount(0);
            }


            String loveUserCommentKey = "QUANZI_COMMENT_LOVE_USER_" + UserThreadLocal.get().getId() + "_" + movements.getId();
            movements.setHasLoved(this.redisTemplate.hasKey(loveUserCommentKey) ? 1 : 0); //是否喜欢

            String loveCommentKey = "QUANZI_COMMENT_LOVE_" + movements.getId();
            String loveValue = this.redisTemplate.opsForValue().get(loveCommentKey);
            if (StringUtils.isNotEmpty(loveValue)) {
                movements.setLoveCount(Integer.valueOf(loveValue)); //喜欢数
            } else {
                movements.setLoveCount(0); //喜欢数
            }
            movementsList.add(movements);
            userIds.add(movements.getUserId());
        }

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);
        List<UserInfo> userInfos = this.userInfoService.queryUserInfoList(queryWrapper);
        for (Movements movements : movementsList) {
            for (UserInfo userInfo : userInfos) {
                if (movements.getUserId().longValue() == userInfo.getUserId().longValue()) {
                    movements.setAge(userInfo.getAge());
                    movements.setAvatar(userInfo.getLogo());
                    movements.setGender(userInfo.getSex().name().toLowerCase(Locale.ROOT));
                    movements.setNickname(userInfo.getNickName());
                    movements.setTags(StringUtils.split(userInfo.getTags(), ","));

                    break;
                }
            }
        }

        pageResult.setItems(movementsList);
        return pageResult;
    }

    //推荐动态
    public PageResult queryRecommendPublishList(Integer page, Integer pageSize) {
        return this.queryPublishList(null, page, pageSize);
    }

    //好友动态
    public PageResult queryUserPublishList(Integer page, Integer pageSize) {
        return this.queryPublishList(UserThreadLocal.get(), page, pageSize);
    }

    /**
     * @Description: 点赞
     * @Param:[publishId]
     * @return:java.lang.Long 点赞数
     * @Author:JinboYang
     * @Date:2021/1/7
     */
    public Long likeComment(String publishId) {
        //直接调用dubbo，进行点赞操作,返回值是false则直接返回null
        boolean bool = this.quanZiApi.saveLikeComment(UserThreadLocal.get().getId(), publishId);
        if (!bool) {
            //保存失败直接返回null
            return null;
        }
        //往redis里面存当前用户点赞信息，以及点赞数+1
        Long likeCount = 0L;
        String likeCommentKey = "QUANZI_COMMENT_LIKE_" + publishId;
        //如果redis里面没有这个key，去查询dubbo，获取点赞数
        if (!redisTemplate.hasKey(likeCommentKey)) {
            Long count = this.quanZiApi.queryCommentCount(publishId, 1);
            likeCount = count;
            this.redisTemplate.opsForValue().set(likeCommentKey, String.valueOf(likeCount));
        } else {
            likeCount = this.redisTemplate.opsForValue().increment(likeCommentKey);
        }

        // 记录当前用于已经点赞 走到这里就说明他一定没有点过赞，直接保存
        String likeUserCommentKey = "QUANZI_COMMENT_LIKE_USER_" + UserThreadLocal.get().getId() + "_" + publishId;
        this.redisTemplate.opsForValue().set(likeUserCommentKey, "1");
        return likeCount;
    }

    /**
     * @Description: 取消喜欢
     * @Param:[publishId]
     * @return:java.lang.Long
     * @Author:JinboYang
     * @Date:2021/1/7
     */
    public Long disLikeComment(String publishId) {
        //remove type=1
        boolean bool = this.quanZiApi.removeComment(UserThreadLocal.get().getId(), publishId, 1);
        //保存失败
        if (!bool) {
            return null;
        }
        //不需要再去判断有没有对应的redisKey，因为取消就代表点过赞了
        String likeCommentKey = "QUANZI_COMMENT_LIKE_" + publishId;
        Long count = this.redisTemplate.opsForValue().decrement(likeCommentKey);

        String likeUserCommentKey = "QUANZI_COMMENT_LIKE_USER_" + UserThreadLocal.get().getId() + "_" + publishId;
        this.redisTemplate.delete(likeUserCommentKey);
        return count;
    }

    /**
     * @Description: 喜欢
     * @Param:[publishId]
     * @return:java.lang.Long
     * @Author:JinboYang
     * @Date:2021/1/7
     */
    public Long loveComment(String publishId) {

        // 保存成功，获取喜欢数
        boolean bool = this.quanZiApi.saveLoveComment(UserThreadLocal.get().getId(), publishId);
        if (!bool) {
            return null;
        }
        Long loveCount = 0L;
        String likeCommentKey = "QUANZI_COMMENT_LOVE_" + publishId;
        if (!this.redisTemplate.hasKey(likeCommentKey)) {
            Long count = this.quanZiApi.queryCommentCount(publishId, 3);
            loveCount = count;
            this.redisTemplate.opsForValue().set(likeCommentKey, String.valueOf(loveCount));
        } else {
            loveCount = this.redisTemplate.opsForValue().increment(likeCommentKey);
        }
        // 记录当前用于已经喜欢
        String likeUserCommentKey = "QUANZI_COMMENT_LOVE_USER_" + UserThreadLocal.get().getId() + "_" + publishId;
        this.redisTemplate.opsForValue().set(likeUserCommentKey, "3");

        return loveCount;
    }

    /**
     * @Description: 取消喜欢
     * @Param:[publishId]
     * @return:java.lang.Long
     * @Author:JinboYang
     * @Date:2021/1/7
     */
    public Long unLoveComment(String publishId) {
        // 保存成功，获取喜欢数
        boolean bool = this.quanZiApi.removeComment(UserThreadLocal.get().getId(), publishId, 3);
        if (!bool) {
            return null;
        }
        String likeCommentKey = "QUANZI_COMMENT_LOVE_" + publishId;
        Long count = this.redisTemplate.opsForValue().decrement(likeCommentKey);
        // 记录当前用于已经喜欢
        String likeUserCommentKey = "QUANZI_COMMENT_LOVE_USER_" + UserThreadLocal.get().getId() + "_" + publishId;
        this.redisTemplate.delete(likeUserCommentKey);

        return count;
    }

    /**
     * @Description: 单条信息查询
     * @Param:[publishId]
     * @return:com.tanhua.server.vo.Movements
     * @Author:JinboYang
     * @Date:2021/1/7
     */
    public Movements queryMovementsById(String publishId) {
        //先调用dubbo服务，查询出单条发布的信息,如果为null直接返回
        Publish publish = this.quanZiApi.queryPublishById(publishId);
        if (publish == null) {
            return null;
        }
        //将Publish转换为Movements,要抽取方法
        List<Movements> movementsList = this.fillValueToMovements(Arrays.asList(publish));
        return movementsList.get(0);

    }

    private List<Movements> fillValueToMovements(List<Publish> records) {
        User user = UserThreadLocal.get();
        List<Movements> movementsList = new ArrayList<>();
        List<Long> userIds = new ArrayList<>();
        for (Publish record : records) {
            Movements movements = new Movements();
            movements.setId(record.getId().toHexString());
            movements.setUserId(record.getUserId());

            if (!userIds.contains(record.getUserId())) {
                userIds.add(record.getUserId());
            }

            String likeUserCommentKey = "QUANZI_COMMENT_LIKE_USER_" + user.getId() + "_" + movements.getId();
            //是否点赞
            movements.setHasLiked(this.redisTemplate.hasKey(likeUserCommentKey) ? 1 : 0);
            String likeCommentKey = "QUANZI_COMMENT_LIKE_" + movements.getId();
            String value = this.redisTemplate.opsForValue().get(likeCommentKey);
            if (StringUtils.isNotEmpty(value)) {
                movements.setLikeCount(Integer.valueOf(value));
            } else {
                movements.setLikeCount(0);
            }

            String loveUserCommentKey = "QUANZI_COMMENT_LOVE_USER_" + user.getId() + "_" + movements.getId();
            //是否喜欢
            movements.setHasLoved(this.redisTemplate.hasKey(loveUserCommentKey) ? 1 : 0);
            String loveCommentKey = "QUANZI_COMMENT_LOVE_" + movements.getId();
            String loveValue = this.redisTemplate.opsForValue().get(loveCommentKey);
            if (StringUtils.isNotEmpty(loveValue)) {
                movements.setLoveCount(Integer.valueOf(loveValue));
            } else {
                movements.setLoveCount(0);
            }
            movements.setDistance("1.2公里"); //TODO 距离
            movements.setCommentCount(30); //TODO 评论数
            movements.setCreateDate(RelativeDateFormat.format(new Date(record.getCreated()))); //发布时间，10分钟前
            movements.setTextContent(record.getText());
            movements.setImageContent(record.getMedias().toArray(new String[]{}));

            movementsList.add(movements);
        }

        QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
        userInfoQueryWrapper.in("user_id", userIds);
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(userInfoQueryWrapper);
        for (Movements movements : movementsList) {
            for (UserInfo userInfo : userInfoList) {
                if (movements.getUserId().longValue() == userInfo.getUserId().longValue()) {

                    movements.setTags(StringUtils.split(userInfo.getTags(), ','));
                    movements.setNickname(userInfo.getNickName());
                    movements.setGender(userInfo.getSex().name().toLowerCase());
                    movements.setAvatar(userInfo.getLogo());
                    movements.setAge(userInfo.getAge());

                    break;
                }
            }
        }
        return movementsList;
    }

    /**
     * @Description: 查询访客列表
     * @Param:[]
     * @return:java.util.List<com.tanhua.server.vo.VisitorsVo>
     * @Author:JinboYang
     * @Date:2021/1/13
     */
    public List<VisitorsVo> queryVisitorsList() {
        User user = UserThreadLocal.get();
        String redisKey = "visitor_date_" + user.getId();
        //如果redis中存在上次查询的时间则按这个时间查询,否则就差前五个
        String data = this.redisTemplate.opsForValue().get(redisKey);
        List<Visitors> visitors = null;
        if (StringUtils.isEmpty(data)) {
            //按数量查询
            visitors = this.visitorsApi.topVisitor(user.getId(), 5);
        } else {
            //按照时间查询
            visitors = this.visitorsApi.topVisitor(user.getId(), Long.valueOf(data));
        }

        if(CollectionUtils.isEmpty(visitors)){
            return null;
        }

        //获取所有的ids
        List<Long> userIds = new ArrayList<>();
        for (Visitors visitor : visitors) {
            userIds.add(visitor.getVisitorUserId());
        }

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        //根据条件查询
        queryWrapper.in("user_id", userIds);
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(queryWrapper);
        List<VisitorsVo> visitorsVoList = new ArrayList<>();

        for (Visitors visitor : visitors) {
            for (UserInfo userInfo : userInfoList) {
                if (visitor.getVisitorUserId().longValue() == userInfo.getUserId().longValue()) {
                    VisitorsVo visitorsVo = new VisitorsVo();
                    visitorsVo.setAge(userInfo.getAge());
                    visitorsVo.setAvatar(userInfo.getLogo());
                    visitorsVo.setGender(userInfo.getSex().name().toLowerCase());
                    visitorsVo.setId(userInfo.getUserId());
                    visitorsVo.setNickname(userInfo.getNickName());
                    visitorsVo.setTags(StringUtils.split(userInfo.getTags(), ','));
                    visitorsVo.setFateValue(visitor.getScore().intValue());

                    visitorsVoList.add(visitorsVo);
                    break;
                }
            }
        }
        return visitorsVoList;
    }

    /**
     * @Description: 自己所有的动态
     * @Param:[page, pageSize, userId]
     * @return:com.tanhua.server.vo.PageResult
     * @Author:JinboYang
     * @Date:2021/1/13
     */
    public PageResult queryAlbumList(Integer page, Integer pageSize, Long userId) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        PageInfo<Publish> pageInfo = this.quanZiApi.queryAlbumList(userId, page, pageSize);
        List<Publish> records = pageInfo.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            return pageResult;
        }
        //直接调用上面封装的方法
        pageResult.setItems(this.fillValueToMovements(records));
        return pageResult;
    }
}
